<template>
  <div class="body">
    <img :src="img" class="img" ref="img" />
    <div class="bottom">
      <div @click="setShow">取消</div>
      <div @click="setData">完成</div>
    </div>
  </div>
</template>

<script>
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
import { setPhoto } from '@/api/info.js'
export default {
  props: ['img'],
  data () {
    return {
      cropper: null
    }
  },
  methods: {
    setShow () {
      this.$emit('setShow')
    },
    setData () {
      // 基于服务端的裁切使用 getData 方法获取裁切参数
      // this.cropper.getData()
      // 纯客户端的裁切使用 getCroppedCanvas 获取裁切的文件对象
      this.cropper.getCroppedCanvas().toBlob(async (blob) => {
        // console.log(blob);
        // 1、如果接口要求 Content-Type 是 application/json，则传递普通js对象
        // photo({
        //   photo: blob
        // })
        /// 2、如果接口要求 Content-Type 是 multipart/form-data，则必须传递 FormData 对象
        const formData = new FormData()
        formData.append('photo', blob)
        await setPhoto(formData)
        this.$emit('setData')
      })
    }
  },
  mounted () {
    const image = this.$refs.img
    this.cropper = new Cropper(image, {
      aspectRatio: 1,
      viewMode: 1,
      dragMode: 'move',
      autoCropArea: 1,
      cropBoxMovable: false,
      cropBoxResizable: false,
      background: false,
      movable: true
    })
  }
}
</script>

<style lang="less" scoped>
.body {
  display: flex;
  align-items: center;
  height: 100%;
}
.img {
  width: 100%;
}
.bottom {
  position: fixed;
  bottom: 0;
  left: 0;
  display: flex;
  justify-content: space-between;
  width: 100%;
  color: #fff;
  font-size: 30px;
  div {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 120px;
    height: 90px;
  }
}
</style>
